/**
 * 
 */
package com.cchr.acms.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cchr.acms.ConfigInfo;
import com.cchr.acms.model.Chapter;
import com.cchr.acms.model.CountryInfo;
import com.cchr.acms.model.User;
import com.cchr.acms.model.UserPassword;
import com.cchr.acms.service.ChapterService;
import com.cchr.acms.service.CountryInfoService;
import com.cchr.acms.service.UserService;
import com.cchr.acms.util.DataTableVO;
import com.cchr.acms.util.HtmlComponentUtil.SelectOption;
import com.cchr.acms.util.PageableDataVO;

/**
 * @author Fanxin Zeng
 *
 */
@Controller
@RequestMapping("/user")
public class UserController {
	@Autowired
    private UserService userService;
	@Autowired
    private JavaMailSender javaMailSender;
	@Autowired
	private ConfigInfo configInfo;
	@Autowired
	private ChapterService chapterService;
	@Autowired
	private CountryInfoService countryInfoService;
	
	public static String[] COUNTRY = {"Afghanistan","Albania","Algeria","American Samoa","Andorra","Angola","Antigua and Barbuda","Argentina","Armenia","Australia","Austria","Azerbaijan","Bahamas","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bermuda","Bhutan","Bolivia","Bosnia and Herzegovina","Botswana","Brazil","Brunei","Bulgaria","Burkina Faso","Burundi","Cambodia","Cameroon","Canada","Cape Verde","Cayman Islands","Central African Republic","Chad","Chile","China","Colombia","Comoros","Congo, Democratic Republic of the","Congo, Republic of the","Costa Rica","Côte d'Ivoire","Croatia","Cuba","Cyprus","Czech Republic","Denmark","Djibouti","Dominica","Dominican Republic","East Timor","Ecuador","Egypt","El Salvador","Equatorial Guinea","Eritrea","Estonia","Ethiopia","Faroe Islands","Fiji","Finland","France","French Polynesia","Gabon","Gambia","Georgia","Germany","Ghana","Greece","Greenland","Grenada","Guam","Guatemala","Guinea","Guinea-Bissau","Guyana","Haiti","Honduras","Hong Kong","Hungary","Iceland","India","Indonesia","Iran","Iraq","Ireland","Israel","Italy","Jamaica","Japan","Jordan","Kazakhstan","Kenya","Kiribati","North Korea","South Korea","Kosovo","Kuwait","Kyrgyzstan","Laos","Latvia","Lebanon","Lesotho","Liberia","Libya","Liechtenstein","Lithuania","Luxembourg","Macedonia","Madagascar","Malawi","Malaysia","Maldives","Mali","Malta","Marshall Islands","Mauritania","Mauritius","Mexico","Micronesia","Moldova","Monaco","Mongolia","Montenegro","Morocco","Mozambique","Myanmar","Namibia","Nauru","Nepal","Netherlands","New Zealand","Nicaragua","Niger","Nigeria","Northern Mariana Islands","Norway","Oman","Pakistan","Palau","Palestine, State of","Panama","Papua New Guinea","Paraguay","Peru","Philippines","Poland","Portugal","Puerto Rico","Qatar","Romania","Russia","Rwanda","Saint Kitts and Nevis","Saint Lucia","Saint Vincent and the Grenadines","Samoa","San Marino","Sao Tome and Principe","Saudi Arabia","Senegal","Serbia","Seychelles","Sierra Leone","Singapore","Sint Maarten","Slovakia","Slovenia","Solomon Islands","Somalia","South Africa","Spain","Sri Lanka","Sudan","Sudan, South","Suriname","Swaziland","Sweden","Switzerland","Syria","Taiwan","Tajikistan","Tanzania","Thailand","Togo","Tonga","Trinidad and Tobago","Tunisia","Turkey","Turkmenistan","Tuvalu","Uganda","Ukraine","United Arab Emirates","United Kingdom","United States","Uruguay","Uzbekistan","Vanuatu","Vatican City","Venezuela","Vietnam","Virgin Islands, British","Virgin Islands, U.S.","Yemen","Zambia","Zimbabwe"};
	
	
    @RequestMapping("/index")
    public String index(HttpServletRequest request){
    	List<String> countries = chapterService.queryAllCountries();
    	List<SelectOption> countryDatas = new ArrayList<SelectOption>();
    	if(countries != null && countries.size() > 0)
    	{
    		for (int i = 0; i < countries.size(); i++) {
        		SelectOption op = new SelectOption();
        		op.setLabel(countries.get(i));
        		op.setValue(countries.get(i));
        		countryDatas.add(op);
    		}
    	}
    	request.setAttribute("countryDatas", countryDatas);
        return "sys/user_list";
    }
    
    @RequestMapping(value={"/getUserListJson"}, method = RequestMethod.POST)
    @ResponseBody
    public PageableDataVO<User> getUserList(DataTableVO dataTableVO, User user){
    	int recordIndex = dataTableVO.getStart();
		int pageNum = dataTableVO.getLength();
		PageableDataVO<User> data = new PageableDataVO<User>();
		List<User> result = userService.queryUser(user, recordIndex, pageNum);
		int cnt = userService.queryUserCount(user);
		data.setiTotalDisplayRecords(cnt);
		data.setiTotalRecords(cnt);
		data.addData(result);
		return data;
    }
    
    @RequestMapping(value="/resetPassword", method = RequestMethod.GET)
    public String resetPassword(HttpServletRequest request, HttpServletResponse resp) throws IOException{
    	return "resetPassword";
    }
    
    @RequestMapping(value="/savePassword", method = RequestMethod.POST)
    public String savePassword(HttpServletRequest request, HttpServletResponse resp) throws IOException{
    	User u = (User)request.getSession().getAttribute("user");
    	if(u==null){
    		return "login";
    	}
    	u = userService.getUserById(u.getId());
    	if(u==null){
    		request.setAttribute("msg", "User Invalid");
    		return "resetPassword";
    	}
    	
    	String originalPassword = u.getPassword();
    	String  oldPassword = request.getParameter("oldPassword");
    	String newPassword = request.getParameter("newPassword");
    	String confirmPassword = request.getParameter("confirmPassword");
    	if(oldPassword == null || oldPassword.length()==0 || !originalPassword.equals(userService.getCrypedSid(oldPassword))){
    		request.setAttribute("error_oldPassword", "Old Password is incorrect");
    		return "resetPassword";
    	}
    	
    	if(newPassword == null || newPassword.length()==0){
    		request.setAttribute("error_newPassword", "New Password is required");
    		return "resetPassword";
    	}
    	
    	if(confirmPassword == null || confirmPassword.length()==0){
    		request.setAttribute("error_confirmPassword", "Confirm Password is required");
    		return "resetPassword";
    	}
    	
    	if(!newPassword.equals(confirmPassword)){
    		request.setAttribute("msg", "New Password and Confirm Password is not consistent");
    		return "resetPassword";
    	}
    	
    	u.setPassword(userService.getCrypedSid(newPassword));
    	u.setLastUpdateDate(new Date());
    	u.setLastUpdatedBy(u.getUserName());
    	userService.updateUser(u);
    	request.getSession().setAttribute("user", u);
    	request.getSession().setAttribute("userName", u.getUserName());
    	request.getSession().setAttribute("email", u.getEmail());
    	request.setAttribute("msg", "Password has been reset successfully!");
    	return "resetPassword";
    }
    
    @RequestMapping(value="/profiles", method = RequestMethod.GET)
    public String profiles(HttpServletRequest request, HttpServletResponse resp) throws IOException{
    	Integer[] pages = {5, 10, 20, 50};
    	User u = (User)request.getSession().getAttribute("user");
    	if(u==null){
    		return "login";
    	}
    	request.setAttribute("pageSizes", pages);
    	request.setAttribute("currentSize", u.getPageSize());
    	return "user/profiles";
    }
    
    @RequestMapping(value="/profiles", method = RequestMethod.POST)
    public String saveProfiles(HttpServletRequest request, HttpServletResponse resp, Integer pageSize) throws IOException{
    	User u = (User)request.getSession().getAttribute("user");
    	User user = userService.getUserById(u.getId());
    	user.setPageSize(pageSize);
    	userService.updateUser(user);
    	request.setAttribute("msg", "Profiles has been saved successfully!");
    	Integer[] pages = {5, 10, 20, 50};
    	request.setAttribute("pageSizes", pages);
    	request.setAttribute("currentSize", pageSize);
    	request.getSession().setAttribute("user", user);
    	return "user/profiles";
    }
    
    @RequestMapping(value="/logout", method = RequestMethod.GET)
    public String logout(HttpServletRequest request) throws IOException{
    	request.getSession().removeAttribute("user");
    	request.getSession().removeAttribute("userName");
    	return "login";
    }
    
    @RequestMapping(value="/login", method = RequestMethod.GET)
    public String loginPage(HttpServletRequest request, HttpServletResponse resp) throws IOException{
    	return "login";
    }
    
    @RequestMapping(value="/login", method = RequestMethod.POST)
    public String login(HttpServletRequest request, HttpServletResponse resp) throws IOException{
    	String email = request.getParameter("signin_email");
    	String password = request.getParameter("signin_password");
    	if(email==null || email.length()==0){
    		request.setAttribute("email_error_msg", "Email required!");
    		return "login";
    	}
    	if(password == null || password.length()==0){
    		request.setAttribute("password_error_msg", "Password required!");
    		return "login";
    	}
    	
    	User u = userService.getUserByEmail(email);
    	String crypedPass = userService.getCrypedSid(password);
    	if(u==null || !crypedPass.equals(u.getPassword()) || u.getStatus() != 2){
    		request.setAttribute("error_msg", "Invalid User or Password!");
    		return "login";
    	}
    	request.getSession().setAttribute("superAdmin", configInfo.getSuperAdmin());
    	request.getSession().setAttribute("userName", u.getUserName());
    	request.getSession().setAttribute("email", u.getEmail());
    	request.getSession().setAttribute("userType", u.getType());
    	request.getSession().setAttribute("user", u);
    	return "redirect:/case/showAbuseList";
    }
    
    @RequestMapping(value={"/detail/{id}"}, method = RequestMethod.GET)
    public String getUserDetail(HttpServletRequest req,@PathVariable Integer id){
    	User user = userService.getUserById(id);
    	
    	req.setAttribute("userInfo", user);
    	return "viewDetail";
    }
    
    @RequestMapping(value={"/detail/{id}"}, method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> getUserById(@PathVariable Integer id){
    	Map<String,Object> data = new HashMap<String,Object>();
    	if(id != null){
    		User user = userService.getUserById(id);
    		Chapter chapter = (Chapter) chapterService.queryChapterById(user.getChapterId());
    		data.put("success", "Y");
			data.put("userId", id);
			data.put("userName", user.getUserName());
			data.put("password", user.getPassword());
			data.put("firstName", user.getFirstName());
			data.put("middleName", user.getMiddleName());
			data.put("lastName", user.getLastName());
			data.put("age", user.getAge());
			data.put("type", user.getType());
			data.put("country", user.getCountry());
			data.put("state", user.getState());
			data.put("city", user.getCity());
			data.put("streetAddress", user.getStreetAddress());
			data.put("zip", user.getZip());
			data.put("email", user.getEmail());
			data.put("telephone", user.getTelephone());
			data.put("status", user.getStatus());
			data.put("type",user.getType());
			if(chapter!=null){
				data.put("chCountry",chapter.getCountry());
				data.put("chStates", chapter.getStates());
				data.put("chCity", chapter.getCity());
				data.put("chapter", chapter.getChapter());
			}
    	}else{
    		data.put("success", "N");
    		data.put("msg", "Invalid Parameter");
    	}
		return data;
    }
    
    @RequestMapping(value={"/save"}, method = RequestMethod.POST)
    @ResponseBody
    public Map<String,String> save(HttpServletRequest req,HttpServletResponse resp) throws IOException{
    	Map<String,String> data = new HashMap<String,String>();
    	String userId=req.getParameter("userId");
    	String userName=req.getParameter("userName");
    	String password=req.getParameter("password");
    	String firstName=req.getParameter("firstName");
    	String middleName=req.getParameter("middleName");
    	String lastName=req.getParameter("lastName");
    	String age=req.getParameter("age");
    	String type=req.getParameter("type");
    	String country=req.getParameter("country");
    	String state=req.getParameter("state");
    	String city=req.getParameter("city");
    	String streetAddress=req.getParameter("streetAddress");
    	String zip=req.getParameter("zip");
    	String email=req.getParameter("email");
    	String status=req.getParameter("status");
    	String telephone = req.getParameter("telephone");
    	String chapterId = req.getParameter("chapterId");
    	System.out.println("Save user information....");
    	if(userName == null || userName.length()==0){
    		data.put("success", "N");
    		data.put("msg", "User Name should be filled!");
    		return data;
    	}
    	
    	if(email == null || email.length()==0){
    		data.put("success", "N");
    		data.put("msg", "Email should be filled!");
    		return data;
    	}
    	
    	if((userId == null || userId.length()==0) && (password == null || password.length() < 6)){
    		data.put("success", "N");
    		data.put("msg", "Password length should be at least 6!");
    		return data;
    	}
    	
    	if(userId != null && userId.length() != 0 && password != null && password.length() > 0 &&  password.length() < 6){
    		data.put("success", "N");
    		data.put("msg", "Password length should be at least 6!");
    		return data;
    	}
    	if(type.equals("3")&&StringUtils.isBlank(country)){
    		data.put("success", "N");
    		data.put("msg", "country should be at filled!");
    		return data;
    	}
    	if(type.equals("3")&&StringUtils.isBlank(chapterId)){
    		data.put("success", "N");
    		data.put("msg", "chapter should be at filled!");
    		return data;
    	}
    	
    	User user = new User();
    	if(!StringUtils.isBlank(chapterId)){
    		user.setChapterId(Integer.valueOf(chapterId));
    	}
    	user.setUserName(userName);
    	user.setFirstName(firstName);
    	user.setMiddleName(middleName);
    	user.setLastName(lastName);
    	user.setAge(age);
    	if(age==null || age.length()==0){
    		user.setAge("0");
    	}
    	user.setType(type);
    	user.setCountry(country);
    	user.setState(state);
    	user.setCity(city);
    	user.setStreetAddress(streetAddress);
    	user.setZip(zip);
    	user.setEmail(email);
    	user.setTelephone(telephone);
    	user.setPageSize(20);
    	if(status==null || status.length()==0){
    		user.setStatus(2);
    	}else{
    		user.setStatus(Integer.parseInt(status));
    	}
    	
    	User u = userService.getUserByEmail(email);
    	if((u != null && (userId == null || userId.length()==0)) || (u != null && u.getId() != Integer.parseInt(userId))){
			data.put("success", "N");
    		data.put("msg", "Email alrady exists!");
    		return data;
		}
    	if(userId != null && userId.length()>0){
    		u = userService.getUserById(Integer.parseInt(userId));
    		if(u==null){
    			data.put("success", "N");
        		data.put("msg", "User not exist!");
        		return data;
    		}
    		
    		if(u.getEmail().equals(configInfo.getSuperAdmin()) && !email.equals(configInfo.getSuperAdmin())){
    			data.put("success", "N");
        		data.put("msg", "Super administrator's email can't be modified!");
        		return data;
    		}
    		if(password == null || password.length() == 0){
    			user.setPassword(u.getPassword());
    		}else{
    			user.setPassword(userService.getCrypedSid(password));
    		}
    		user.setId(Integer.parseInt(userId));
    		user.setLastUpdatedBy(req.getSession().getAttribute("userName")==null?"":req.getSession().getAttribute("userName").toString());
    		user.setLastUpdateDate(new Date());
    		userService.updateUser(user);
    		
    		User us = (User)req.getSession().getAttribute("user");
    		if(us != null && us.getId() == user.getId()){
    			req.getSession().setAttribute("user", user);
    			req.getSession().setAttribute("userName", user.getUserName());
    			req.getSession().setAttribute("email", user.getEmail());
    			req.getSession().setAttribute("userType", user.getType());
    		}
    	}else{
    		user.setPassword(userService.getCrypedSid(password));
    		user.setCreatedBy(req.getSession().getAttribute("userName")==null?"":req.getSession().getAttribute("userName").toString());
    		user.setCreateDate(new Date());
    		userService.insertUser(user);
    	}
    	    	
    	data.put("success", "Y");
    	return data;
    }
    
    @RequestMapping(value={"/delete"}, method = RequestMethod.POST)
    @ResponseBody
    public Map<String,String> delete(HttpServletRequest req,HttpServletResponse resp) throws IOException{
    	String userId=req.getParameter("userId");
    	Map<String,String> data = new HashMap<String,String>();
    	User u = userService.getUserById(Integer.parseInt(userId));
    	if(u.getEmail().equals(configInfo.getSuperAdmin())){
    		data.put("success", "N");
    		data.put("msg", "Super admin's email can't be deleted!");
    		return data;
    	}
    	userService.deleteUser(Integer.parseInt(userId));
    	data.put("success", "Y");
    	return data;
    }
    
    @RequestMapping(value="/getPassword", method = RequestMethod.GET)
    public String getPassword(HttpServletRequest request, HttpServletResponse resp) throws IOException{
    	return "getPassword";
    }
    
    @RequestMapping(value="/sendEmail", method = RequestMethod.POST)
    public String sendEmail(HttpServletRequest request, HttpServletResponse resp) throws IOException{
    	String email = request.getParameter("email");
    	request.setAttribute("email", email);
    	if(email == null || email.length()==0){
    		request.setAttribute("error_email", "User Email is required");
    		return "getPassword";
    	}
    	User u = (User)userService.getUserByEmail(email);
    	if(u==null){
    		request.setAttribute("msg", "User Invalid");
    		return "getPassword";
    	}
    	
    	UserPassword userPassword = userService.getUserPasswordByUserName(email);
    	String sid = userService.getCrypedSid(u.getUserName()+System.currentTimeMillis()+u.getEmail()+(new Random(100000).nextLong()));
    	SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
    	simpleMailMessage.setFrom("CCHR-Admin");
    	simpleMailMessage.setTo(u.getEmail());  
    	simpleMailMessage.setSubject("Password reset");  
    	simpleMailMessage.setText("To verify this email address belongs to you, click the link below and then sign in using your password."+
    			configInfo.getMainUrl()+"/user/linkCheck?sid="+sid+"&userName="+email);  
    	if(userPassword==null){
    		userPassword = new UserPassword();
    	    Date now = new Date();
    	    userPassword.setSid(sid);
    	    userPassword.setUserName(email);
    	    userPassword.setCreateDate(now);
    	    userPassword.setExpiredDate(new Date(now.getTime() + 2*60*60*1000));
    	    userService.insertUserPassword(userPassword);
    	}else{
    	    Date now = new Date();
     	    userPassword.setSid(sid);
     	    userPassword.setUserName(email);
     	    userPassword.setCreateDate(now);
     	    userPassword.setExpiredDate(new Date(now.getTime() + 2*60*60*1000));
     	    userService.updateUser(userPassword);
    	}
    	javaMailSender.send(simpleMailMessage);
    	request.setAttribute("msg", "Please click the link that sent to your Email to reset your password within 2 hours!");
    	
    	return "message";
    }
    
    @RequestMapping(value="/linkCheck", method = RequestMethod.GET)
    public String linkCheck(HttpServletRequest request, HttpServletResponse resp) throws IOException{
    	String userName = request.getParameter("userName");
    	String sid = request.getParameter("sid");
    	UserPassword userPassword = (UserPassword)userService.getUserPasswordByUserName(userName);
    	
    	if(userPassword==null || !userPassword.getSid().equals(sid)){
    		request.setAttribute("msg", "URL Invalid ");
        	return "message";
    	}
    	
    	if(userPassword.getExpiredDate().before(new Date())){
    		request.setAttribute("msg", "URL Invalid ");
        	return "message";
    	}
    	request.setAttribute("userName", userName);
    	request.setAttribute("sid", sid);
    	return "modifypassword";
    }
    
    @RequestMapping(value="/updatePassword", method = RequestMethod.POST)
    public String updatePassword(HttpServletRequest request, HttpServletResponse resp) throws IOException{
    	String email = request.getParameter("userName");
    	String sid = request.getParameter("sid");
    	request.setAttribute("userName", email);
    	request.setAttribute("sid", sid);
    	UserPassword userPassword = (UserPassword)userService.getUserPasswordByUserName(email);
    	
    	if(userPassword==null || !userPassword.getSid().equals(sid)){
    		request.setAttribute("msg", "Invalid Operation");
        	return "modifypassword";
    	}
    	
    	if(userPassword.getExpiredDate().before(new Date())){
    		request.setAttribute("msg", "Expired Operation");
        	return "modifypassword";
    	}
    	
    	User u = userService.getUserByEmail(email);
    	if(u==null){
    		request.setAttribute("msg", "User Invalid");
    		return "modifypassword";
    	}
    	String newPassword = request.getParameter("newPassword");
    	String confirmPassword = request.getParameter("confirmPassword");
    	if(newPassword == null || newPassword.length()==0){
    		request.setAttribute("error_newPassword", "New Password is required");
    		return "modifypassword";
    	}
    	
    	if(confirmPassword == null || confirmPassword.length()==0){
    		request.setAttribute("error_confirmPassword", "Confirm Password is required");
    		return "modifypassword";
    	}
    	
    	if(!newPassword.equals(confirmPassword)){
    		request.setAttribute("msg", "New Password and Confirm Password is not consistent");
    		return "modifypassword";
    	}
    	u.setPassword(userService.getCrypedSid(newPassword));
    	u.setLastUpdateDate(new Date());
    	u.setLastUpdatedBy(u.getUserName());
    	userService.updateUser(u);
    	userService.deleteUserPasswordByUserName(email);
    	request.setAttribute("msg", "Password has been reset successfully!");
    	return "message";
    }
    
	@RequestMapping(value={"/addUser"}, method = RequestMethod.GET)
	public String addUser(HttpServletRequest request){
		List<String> countries = chapterService.queryAllCountries();
    	List<SelectOption> countryDatas = new ArrayList<SelectOption>();
    	if(countries != null && countries.size() > 0)
    	{
    		for (int i = 0; i < countries.size(); i++) {
        		SelectOption op = new SelectOption();
        		op.setLabel(countries.get(i));
        		op.setValue(countries.get(i));
        		countryDatas.add(op);
    		}
    	}
    	request.setAttribute("countryDatas", countryDatas);
        return "case/addUser";
	}
	
	@RequestMapping(value={"/chapters"})
	public String getChapters(HttpServletRequest request){
		List<SelectOption> countryDatas = new ArrayList<SelectOption>();
    	for (int i = 0; i < COUNTRY.length; i++) {
    		SelectOption op = new SelectOption();
    		op.setLabel(COUNTRY[i]);
    		op.setValue(COUNTRY[i]);
    		countryDatas.add(op);
		}
    	request.setAttribute("countryDatas", countryDatas);
		 return "sys/chapter_list";
	}
	
    @RequestMapping(value={"/getChapterListJson"}, method = RequestMethod.POST)
    @ResponseBody
    public PageableDataVO<Chapter> getChapterList(DataTableVO dataTableVO, Chapter chapter){
    	int recordIndex = dataTableVO.getStart();
		int pageNum = dataTableVO.getLength();
		PageableDataVO<Chapter> data = new PageableDataVO<Chapter>();
		List<Chapter> result = chapterService.queryChapter(chapter, recordIndex, pageNum);
		int cnt = chapterService.queryChapterCount(chapter);
		data.setiTotalDisplayRecords(cnt);
		data.setiTotalRecords(cnt);
		data.addData(result);
		return data;
    }
    
	@RequestMapping(value={"/getCountry"}, method = RequestMethod.POST)
	@ResponseBody
	public List<String> getCountry(HttpServletRequest request){
        return countryInfoService.getAllCountry();
	}

	@RequestMapping(value={"/GetStatesByCountry"}, method = RequestMethod.POST)
	@ResponseBody
	public List<String> GetStatesByCountry(HttpServletRequest request){
		String country = request.getParameter("country");
        return countryInfoService.getStatesByCountry(country);
	}
	
	@RequestMapping(value={"/GetCityByCryandStates"}, method = RequestMethod.POST)
	@ResponseBody
	public List<String> GetCityByCryandStates(HttpServletRequest request){
		String country = request.getParameter("country");
		String states = request.getParameter("states");
		CountryInfo info = new CountryInfo();
		info.setCountry(country);
		info.setStates(states);
        return countryInfoService.getCityByCryandStates(info);
	}
	
    @RequestMapping(value={"/saveChapter"}, method = RequestMethod.POST)
    @ResponseBody
    public Map<String,String> addChapter(Chapter chapter) throws IOException{
    	Map<String,String> data = new HashMap<String,String>();
    	if(StringUtils.isBlank(chapter.getCountry())){
    		data.put("success", "N");
    		data.put("msg", "country should be filled!!");
    		return data;
    	}
    	if(StringUtils.isBlank(chapter.getStates())){
    		data.put("success", "N");
    		data.put("msg", "states/province should be filled!!");
    		return data;
    	}
    	if(StringUtils.isBlank(chapter.getChapter())){
    		data.put("success", "N");
    		data.put("msg", "chapter should be filled!!");
    		return data;
    	}
		//先判断这条记录是否存在
		int num = chapterService.queryChapterCount(chapter);
		if(num>0){
    		data.put("success", "N");
    		data.put("msg", "this chapter has already exist!");
    		return data;
		}
		if(chapter.getId() == null)
		{
			int flag = chapterService.insertChapter(chapter);
			if(flag<0){
	    		data.put("success", "N");
	    		data.put("msg", "add chapter information failed!");
	    		return data;
			}
		}
		else
		{
			int flag = chapterService.updateChapter(chapter);
			if(flag<0){
	    		data.put("success", "N");
	    		data.put("msg", "add chapter information failed!");
	    		return data;
			}
		}
    	data.put("success", "Y");
    	return data;
    	
    }
    
    @RequestMapping(value={"/deleteChapter"}, method = RequestMethod.POST)
    @ResponseBody
    public Map<String,String> deleteChapter(HttpServletRequest req,HttpServletResponse resp) throws IOException{
    	String chapterId=req.getParameter("chapterId");
    	Map<String,String> data = new HashMap<String,String>();
    	chapterService.deleteChapter(Integer.parseInt(chapterId));
    	data.put("success", "Y");
    	return data;
    }
    
	@RequestMapping(value={"/GetChapters"}, method = RequestMethod.POST)
	@ResponseBody
	public List<Chapter> GetChapters(HttpServletRequest request){
		String country = request.getParameter("country");
		String states = request.getParameter("states"); 
		Chapter chapter = new Chapter();
	    chapter.setCountry(country);
		chapter.setStates(states);
        return chapterService.queryAllChapter(chapter);
	}
	
    @RequestMapping(value={"/getChapterInfo/{id}"}, method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> getChapterInfo(@PathVariable Integer id){
    	Map<String,Object> data = new HashMap<String,Object>();
    	if(id != null){
    		Chapter chapter = chapterService.queryChapterById(id);
    		if(chapter != null){
    			data.put("success", "Y");
    			data.put("country", chapter.getCountry());
    			data.put("states", chapter.getStates());
    			data.put("city", chapter.getCity());
    			data.put("chapter", chapter.getChapter());
    			data.put("id", chapter.getId());
    		}else{
    			data.put("success", "N");
    			data.put("msg", "User not exists");
    		}
    	}else{
    		data.put("success", "N");
    		data.put("msg", "Invalid Parameter");
    	}
		return data;
    }
    
}